<template>
  <div class="w-full">
    <div class="flex justify-end">
      <MciButton icon="mci-icon-add" type="primary" :link="true" @click="handleAdd"> 申请 </MciButton>
    </div>
    <MciSubCard>
      <AppList ref="appListRef" />
      <mci-dialog
        v-model="showApply"
        title="申请"
        width="600"
        draggable
        :confirm-handle="handleConfirm"
        @close="handleClosed"
      >
        <AppApply ref="appApplyRef" @change="handleChange" />
      </mci-dialog>
    </MciSubCard>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { MciButton, MciSubCard, MciDialog } from '@/components/base';
import AppList from './app-list/index.vue';
import AppApply from './app-apply/index.vue';
import { ApplyAppForm } from '../data';
import { postAppApply } from '@/api/decision-engine';
import type { IPostAppApplyReq } from '@/api/decision-engine';

// 申请弹窗
const appApplyRef = ref();
const showApply = ref(false);
const appListRef = ref();
let applyParam :ApplyAppForm = {
  appName: '',
  callbackUrl:''
};

const handleAdd = () => {
  showApply.value = true;
};

const handleChange =(formData: ApplyAppForm) => {
  applyParam = formData;
};

// 确定操作
const handleConfirm = () => {
  if (!applyParam.appName) {
    return;
  }
  addRequest();
};

// 新增请求
const addRequest = async () => {
  const params: IPostAppApplyReq = {
    appName: applyParam.appName,
    callbackUrl: applyParam.callbackUrl
  };
  await postAppApply(params);
  // if (data) {
    handleClosed();
    appListRef.value && appListRef.value.tableRequest();
  // }
};

// 取消申请
const handleClosed = () => {
  appApplyRef.value?.resetForm();
  showApply.value = false;
};

</script>
